// Rust学习智能体前端应用 - 挑战系统
class RustChallengeApp {
    constructor() {
        this.currentUserId = 'web_user';
        this.currentChallenge = null;
        this.currentLevelIndex = 0;
        this.currentTopic = null;
        this.challengesData = null;
        this.completedChallenges = [];
        this.init();
    }

    async init() {
        await this.loadChallenges();
        this.renderTopicLevels();
        this.updateUserProgress();
    }

    // 加载挑战数据
    async loadChallenges() {
        try {
            const response = await fetch('/api/challenges?user_id=web_user');
            const data = await response.json();
            this.challengesData = data.challenges;
        } catch (error) {
            console.error('Failed to load challenges:', error);
        }
    }

    // 更新用户进度
    updateUserProgress() {
        if (!this.challengesData) return;
        
        const totalChallenges = Object.values(this.challengesData).reduce((total, topic) => total + topic.levels.length, 0);
        const completedCount = this.completedChallenges.length;
        const progressPercentage = totalChallenges > 0 ? (completedCount / totalChallenges) * 100 : 0;
        
        document.getElementById('userProgress').textContent = `${completedCount}/${totalChallenges} 完成`;
        document.getElementById('progressFill').style.width = `${progressPercentage}%`;
    }

    // 渲染主题关卡
    renderTopicLevels() {
        const container = document.getElementById('topicLevels');
        container.innerHTML = '';

        if (!this.challengesData) return;

        Object.entries(this.challengesData).forEach(([topicId, topicData]) => {
            const card = this.createTopicCard(topicId, topicData);
            container.appendChild(card);
        });
    }

    // 创建主题卡片
    createTopicCard(topicId, topicData) {
        const card = document.createElement('div');
        card.className = 'topic-card';
        card.onclick = () => this.enterTopic(topicId);

        // 根据主题ID获取对应的样式类
        const iconClass = `topic-${topicId}`;
        const icon = this.getTopicIcon(topicId);

        const levelsHtml = topicData.levels.map((level, index) => {
            const status = this.getLevelStatus(topicId, index);
            return `<div class="level-dot ${status}">${index + 1}</div>`;
        }).join('');

        card.innerHTML = `
            <div class="topic-header">
                <div class="topic-icon ${iconClass}">${icon}</div>
                <div class="topic-info">
                    <h3>${topicData.title}</h3>
                    <p>${topicData.description}</p>
                </div>
            </div>
            <div class="levels-preview">
                ${levelsHtml}
            </div>
        `;

        return card;
    }

    // 获取主题图标
    getTopicIcon(topicId) {
        const icons = {
            'ownership': '🔑',
            'borrowing': '🔗',
            'lifetimes': '⏳',
            'traits': '🎭',
            'error-handling': '⚠️',
            'closures': '📦',
            'concurrency': '🚀',
            'macros': '🔧',
            'pattern-matching': '🎯',
            'iterators': '🔄'
        };
        return icons[topicId] || '📚';
    }

    // 获取关卡状态
    getLevelStatus(topicId, levelIndex) {
        const challengeId = `${topicId}_${levelIndex + 1}`;
        if (this.completedChallenges.includes(challengeId)) {
            return 'completed';
        }
        // 如果是第一个关卡或者是前一个关卡已完成
        if (levelIndex === 0 || this.completedChallenges.includes(`${topicId}_${levelIndex}`)) {
            return 'current';
        }
        return 'locked';
    }

    // 进入主题
    enterTopic(topicId) {
        this.currentTopic = topicId;
        this.currentLevelIndex = 0;
        
        // 找到第一个未完成的关卡
        const topic = this.challengesData[topicId];
        for (let i = 0; i < topic.levels.length; i++) {
            const challengeId = `${topicId}_${i + 1}`;
            if (!this.completedChallenges.includes(challengeId)) {
                this.currentLevelIndex = i;
                break;
            }
        }
        
        this.loadChallenge();
    }

    // 加载挑战
    loadChallenge() {
        if (!this.challengesData || !this.currentTopic) return;

        const topic = this.challengesData[this.currentTopic];
        const level = topic.levels[this.currentLevelIndex];

        if (!level) return;

        this.currentChallenge = level;

        // 更新UI
        document.getElementById('challengeTitle').textContent = level.title;
        document.getElementById('levelSelector').style.display = 'none';
        document.getElementById('challengeView').style.display = 'block';

        // 渲染代码模板
        this.renderCodeTemplate(level.code_template);
        this.renderFragments(level.code_fragments);
    }

    // 渲染代码模板
    renderCodeTemplate(template) {
        const container = document.getElementById('codeTemplate');
        container.innerHTML = '';

        template.forEach((line, index) => {
            const lineDiv = document.createElement('div');
            lineDiv.className = 'code-line';
            
            // 检查是否有空白处
            const hasBlank = line.includes('_____');
            
            if (hasBlank) {
                const parts = line.split('_____');
                lineDiv.innerHTML = `
                    <span class="code-line-number">${index + 1}</span>
                    ${parts[0]}
                    <span class="blank-spot" data-position="0" ondrop="window.rustChallengeApp.dropFragment(event)" ondragover="window.rustChallengeApp.allowDrop(event)">拖拽代码</span>
                    ${parts[1] || ''}
                `;
            } else {
                lineDiv.innerHTML = `
                    <span class="code-line-number">${index + 1}</span>
                    ${line}
                `;
            }
            
            container.appendChild(lineDiv);
        });
    }

    // 渲染代码片段
    renderFragments(fragments) {
        const container = document.getElementById('fragmentList');
        container.innerHTML = '';

        fragments.forEach(fragment => {
            const fragmentDiv = document.createElement('div');
            fragmentDiv.className = 'fragment-item';
            fragmentDiv.draggable = true;
            fragmentDiv.textContent = fragment.code;
            fragmentDiv.dataset.id = fragment.id;
            fragmentDiv.dataset.correct = fragment.correct;
            fragmentDiv.dataset.hint = fragment.hint;

            fragmentDiv.ondragstart = (e) => {
                e.dataTransfer.setData('text/plain', fragment.code);
                e.dataTransfer.setData('text/fragmentId', fragment.id);
                fragmentDiv.classList.add('dragging');
            };

            fragmentDiv.ondragend = () => {
                fragmentDiv.classList.remove('dragging');
            };

            container.appendChild(fragmentDiv);
        });
    }

    // 拖拽处理
    allowDrop(e) {
        e.preventDefault();
        e.target.classList.add('drag-over');
    }

    dropFragment(e) {
        e.preventDefault();
        e.target.classList.remove('drag-over');
        
        const code = e.dataTransfer.getData('text/plain');
        const fragmentId = e.dataTransfer.getData('text/fragmentId');
        
        if (e.target.classList.contains('blank-spot')) {
            e.target.textContent = code;
            e.target.dataset.fragmentId = fragmentId;
            e.target.classList.add('filled');
            
            // 禁用已使用的片段
            const fragmentItem = document.querySelector(`[data-id="${fragmentId}"]`);
            if (fragmentItem) {
                fragmentItem.classList.add('used');
                fragmentItem.draggable = false;
            }
        }
    }

    // 检查答案
    checkAnswer() {
        if (!this.currentChallenge) return;

        const blanks = document.querySelectorAll('.blank-spot.filled');
        const answers = Array.from(blanks).map(blank => blank.textContent.trim());
        const correctAnswers = this.currentChallenge.correct_answer;

        // 检查答案是否正确
        const isCorrect = JSON.stringify(answers.sort()) === JSON.stringify(correctAnswers.sort());

        if (isCorrect) {
            // 标记当前挑战为已完成
            const challengeId = `${this.currentTopic}_${this.currentLevelIndex + 1}`;
            if (!this.completedChallenges.includes(challengeId)) {
                this.completedChallenges.push(challengeId);
                this.updateUserProgress();
            }
            
            this.showResult(true, this.currentChallenge.explanation);
        } else {
            this.showResult(false);
        }
    }

    // 显示结果
    showResult(isCorrect, explanation = '') {
        const modal = document.getElementById('resultModal');
        const icon = document.getElementById('resultIcon');
        const title = document.getElementById('resultTitle');
        const message = document.getElementById('resultMessage');
        const explanationDiv = document.getElementById('explanation');
        const explanationText = document.getElementById('explanationText');
        const nextBtn = document.getElementById('modalNextBtn');

        if (isCorrect) {
            icon.textContent = '🎉';
            title.textContent = '恭喜通过！';
            message.textContent = '你成功完成了这个挑战！';
            explanationDiv.style.display = explanation ? 'block' : 'none';
            if (explanation) {
                explanationText.textContent = explanation;
            }
            nextBtn.style.display = 'block';
        } else {
            icon.textContent = '😔';
            title.textContent = '再试一次！';
            message.textContent = '答案不正确，看看提示再试试吧！';
            explanationDiv.style.display = 'none';
            nextBtn.style.display = 'none';
        }

        modal.style.display = 'block';
    }

    // 关闭结果模态框
    closeResult() {
        document.getElementById('resultModal').style.display = 'none';
    }

    // 下一关
    nextLevel() {
        if (!this.challengesData || !this.currentTopic) return;

        const topic = this.challengesData[this.currentTopic];
        if (this.currentLevelIndex < topic.levels.length - 1) {
            this.currentLevelIndex++;
            this.loadChallenge();
        } else {
            this.showLevelSelector();
        }
    }

    // 重置挑战
    resetChallenge() {
        if (!this.currentChallenge) return;

        // 清除所有填充的空白
        const blanks = document.querySelectorAll('.blank-spot.filled');
        blanks.forEach(blank => {
            blank.textContent = '拖拽代码';
            blank.classList.remove('filled');
            delete blank.dataset.fragmentId;
        });

        // 重新启用所有片段
        const fragments = document.querySelectorAll('.fragment-item.used');
        fragments.forEach(fragment => {
            fragment.classList.remove('used');
            fragment.draggable = true;
        });
    }

    // 返回关卡选择
    showLevelSelector() {
        document.getElementById('challengeView').style.display = 'none';
        document.getElementById('levelSelector').style.display = 'block';
        this.currentChallenge = null;
        this.renderTopicLevels(); // 重新渲染以更新状态
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    window.rustChallengeApp = new RustChallengeApp();
    
    // 全局函数
    window.showLevelSelector = () => window.rustChallengeApp.showLevelSelector();
    window.checkAnswer = () => window.rustChallengeApp.checkAnswer();
    window.resetChallenge = () => window.rustChallengeApp.resetChallenge();
    window.nextLevel = () => window.rustChallengeApp.nextLevel();
    window.nextLevelFromModal = () => window.rustChallengeApp.nextLevel();
    window.closeResult = () => window.rustChallengeApp.closeResult();
    
    // 点击模态框外部关闭
    document.getElementById('resultModal').addEventListener('click', function(e) {
        if (e.target === this) {
            window.rustChallengeApp.closeResult();
        }
    });
});